Du kan inte välja fler än 25 ämnen Ämnen måste starta med en bokstav eller siffra, kan innehålla bindestreck ('-') och vara max 35 tecken långa.
 
 
 
 

96 rader
3.2 KiB

  1. /**
  2. * 服务端 API 代理 —— 将 /api/** 请求转发到 ThinkJS 后端
  3. *
  4. * 对齐 ai_uniapp_v2 H5 端的 manifest.json devServer.proxy 行为:
  5. * /api/user/info → https://api.jiefuku.com/user/info
  6. *
  7. * 用途:
  8. * 1. 避免浏览器跨域
  9. * 2. 服务端转发自动携带 cookie,保持登录态
  10. *
  11. * 环境变量 NUXT_PUBLIC_API_BASE 可覆盖目标地址(生产环境指向 https://api.aionline.cc)
  12. */
  13. import { proxyRequest, sendWebResponse } from 'h3'
  14. export default defineEventHandler(async (event) => {
  15. const config = useRuntimeConfig(event)
  16. const apiBase = String(config.public.apiBase || '').replace(/\/+$/, '')
  17. if (!apiBase) {
  18. throw createError({
  19. statusCode: 500,
  20. statusMessage: 'NUXT_PUBLIC_API_BASE is not configured',
  21. })
  22. }
  23. // 去掉 /api 前缀,得到真实后端路径
  24. let path = event.path.replace(/^\/api/, '') || '/'
  25. if (!path.startsWith('/')) path = '/' + path
  26. const method = event.method
  27. const url = apiBase + path
  28. const headers = {}
  29. // 转发用户 cookie(保持登录态)
  30. const cookie = event.headers.get('cookie')
  31. if (cookie) {
  32. headers.cookie = cookie
  33. }
  34. // 透传客户端的 Content-Type(multipart/form-data 上传需要)
  35. const contentType = event.headers.get('content-type')
  36. if (contentType) {
  37. headers['content-type'] = contentType
  38. }
  39. const isMultipart = Boolean(contentType?.includes('multipart/form-data'))
  40. // 透传签名的 header(nonce / timestr / token)
  41. const clientNonce = event.headers.get('nonce')
  42. const clientTimestr = event.headers.get('timestr')
  43. const clientToken = event.headers.get('token')
  44. const clientAccept = event.headers.get('accept')
  45. if (clientNonce) headers.nonce = clientNonce
  46. if (clientTimestr) headers.timestr = clientTimestr
  47. if (clientToken) headers.token = clientToken
  48. if (clientAccept) headers.accept = clientAccept
  49. const fetchOptions = { method, headers }
  50. // GET: 查询参数
  51. const query = getQuery(event)
  52. const queryStr = new URLSearchParams(query).toString()
  53. const fullUrl = queryStr ? url + '?' + queryStr : url
  54. // Multipart 必须直接转发原始请求流。先 readRawBody() 在部分 Chromium /
  55. // Nitro 组合下会一直等待流结束,导致上传请求既不到后端也不返回。
  56. if (isMultipart) {
  57. return proxyRequest(event, fullUrl, { headers })
  58. }
  59. // POST: 请求体
  60. if (method === 'POST') {
  61. const body = await readBody(event)
  62. if (body && typeof body === 'object') {
  63. fetchOptions.body = new URLSearchParams(body).toString()
  64. }
  65. }
  66. try {
  67. // SSE 必须透传原始 Web Response;$fetch 会等待响应结束并尝试解析,
  68. // 导致浏览器无法逐块收到上游事件。
  69. // Multipart 同样使用原生 fetch,确保二进制请求体和 boundary 原样到达上游。
  70. if ((clientAccept || '').includes('text/event-stream')) {
  71. const upstreamResponse = await fetch(fullUrl, fetchOptions)
  72. return sendWebResponse(event, upstreamResponse)
  73. }
  74. return await $fetch(fullUrl, fetchOptions)
  75. } catch (error) {
  76. console.error('[Server Proxy Error]', url, error.message)
  77. return {
  78. code: 1000,
  79. data: null,
  80. msg: '服务器代理请求失败',
  81. }
  82. }
  83. })